package cn.symbio.pet.service.impl;

import cn.symbio.basic.config.BussinessException;
import cn.symbio.basic.util.BaiduAuditUtils;
import cn.symbio.basic.util.FreemarkUtil;
import cn.symbio.pet.domain.Pet;
import cn.symbio.pet.domain.PetDetail;
import cn.symbio.pet.domain.PetOnlineAuditLog;
import cn.symbio.pet.domain.PetType;
import cn.symbio.pet.mapper.PetDetailMapper;
import cn.symbio.pet.mapper.PetMapper;
import cn.symbio.pet.mapper.PetOnlineAuditLogMapper;
import cn.symbio.pet.mapper.PetTypeMapper;
import cn.symbio.pet.service.IPetService;
import cn.symbio.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bitter
 * @since 2022-10-28
 */
@Service
public class PetServiceImpl extends BaseServiceImpl<Pet> implements IPetService {


    @Autowired
    private PetMapper petMapper;

    @Autowired
    private PetTypeMapper petTypeMapper;

    @Autowired
    private PetDetailMapper petDetailMapper;

    @Autowired
    private PetOnlineAuditLogMapper petOnlineAuditLogMapper;

    /**
     * 修改连同详细表修改
     * @param pet
     */
    @Override
    public void update(Pet pet) {
        super.update(pet);
        PetDetail petDetail = petDetailMapper.findByPetId(pet.getId());
        petDetail.setIntro(pet.getDetail().getIntro());
        petDetail.setAdoptNotice(pet.getDetail().getAdoptNotice());
        petDetailMapper.update(petDetail);
    }

    /**
     * 宠物类型树
     * @return
     */
    @Override
    public List<PetType> tree() {
        List<PetType> all = petTypeMapper.findAll();
        List<PetType> result = new ArrayList<>();
        Map<Long, PetType> map = all.stream().collect(Collectors.toMap(PetType::getId, pet -> pet));
        for (PetType petType : all) {
            if (petType.getPid() == null) {
                result.add(petType);
            } else {
                PetType petType1 = map.get(petType.getPid());
                List<PetType> children = petType1.getChildren();
                children.add(petType);
            }
        }
        return result;
    }

    /**
     * 上架
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public void onsale(List<Long> ids) {
        Date date = new Date();
        StringBuilder sb = new StringBuilder();
        PetOnlineAuditLog petOnlineAuditLog = new PetOnlineAuditLog();
        // stream通过id获取数据查询
        Map<Long, Pet> petMap = petMapper.findAll().stream()
                .filter(pet -> pet.getState() == 0)
                .collect(Collectors.toMap(Pet::getId, pet -> pet));
        for (Long id : ids) {
            Pet pet = petMap.get(id);
            if (!BaiduAuditUtils.TextCensor(pet.getName())){
                sb.append("宠物上架百度AI审核名称失败，宠物名称为：" + pet.getName() + ";");
            }
            if (pet.getResources().split(",").length > 1){
                if (!BaiduAuditUtils.ImgCensor(pet.getResources().split(",")[0])){
                    sb.append("宠物上架百度AI审核图片失败，宠物图片地址为：" + pet.getResources() + ";");
                }
            }else {
                if (!BaiduAuditUtils.ImgCensor(pet.getResources())){
                    sb.append("宠物上架百度AI审核图片失败，宠物图片地址为：" + pet.getResources() + ";");
                }
            }

            // 判断AI校验是否成功
            if (sb.length() > 0){
                // 存日志
                petOnlineAuditLog.setPetId(pet.getId());
                petOnlineAuditLog.setAuditTime(date);
                petOnlineAuditLog.setState(0);
                petOnlineAuditLog.setNote(sb.toString());
                petOnlineAuditLogMapper.add(petOnlineAuditLog);
                continue;
            }
            // 添加通过日志
            petOnlineAuditLog.setPetId(pet.getId());
            petOnlineAuditLog.setState(1);
            petOnlineAuditLog.setAuditTime(date);
            petOnlineAuditLog.setNote("校验合规，上架成功！！");
            petOnlineAuditLogMapper.add(petOnlineAuditLog);
            // 修改状态
            pet.setState(1);
            pet.setOnsaletime(date);
            petMapper.update(pet);

            // 上架通过模板生成页面
            try {
                FreemarkUtil.testHtml(pet.getId());
            } catch (Exception e) {
                e.printStackTrace();
                throw new BussinessException("模板生成失败");
            }
        }
    }

    /**
     * 下架
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public void offsale(List<Long> ids) {
        // 修改状态
        petMapper.batchUpdate(ids);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @Override
    public void batchDel(List<Long> ids) {
        petMapper.batchDel(ids);
    }

    @Override
    public Pet findByPetId(Long id) {
        return petMapper.findByPetId(id);
    }

    @Override
    public void add(Pet pet) {
        super.add(pet);
        pet.getDetail().setPetId(pet.getId());
        petDetailMapper.add(pet.getDetail());
    }
}
